import {Inject, Injectable, Logger} from '@nestjs/common';
import {PassportStrategy} from '@nestjs/passport';
import {ExtractJwt, Strategy} from 'passport-jwt';

import {ISecurityConfig, SecurityConfig} from '~/config';

import {AuthStrategy} from '../auth.constant';
import {UserService} from '~/modules/user/user.service';
import {UserRole} from '~/modules/system/role/role.constant';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, AuthStrategy.JWT) {
  private readonly logger = new Logger(JwtStrategy.name);

  constructor(
    @Inject(SecurityConfig.KEY) private securityConfig: ISecurityConfig,
    private readonly userService: UserService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: securityConfig.jwtSecret,
    });
  }

  /**
   * 验证用户，返回用户信息 - request.user
   * @param payload
   * @returns
   */
  async validate(payload: IAuthUser) {
    const {role, admin, wechat, tenant, status, isAdmin, isSuperAdmin} = await this.userService.getAccountInfo(
      payload.uid
    );

    return {
      ...payload,
      role,
      admin,
      wechat,
      tenant,
      status,
      isAdmin,
      isSuperAdmin,
    };
  }
}
